import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { studentAPI } from '../api'

export const useStudentStore = defineStore('student', () => {
  // 状态
  const studentInfo = ref(null)
  const registrationStatus = ref(null)
  const paymentInfo = ref(null)
  const paymentHistory = ref([])
  const classInfo = ref(null)
  const dormitoryInfo = ref(null)
  const notices = ref([])
  const schedule = ref([])
  const contactInfo = ref(null)
  const isLoading = ref(false)

  // 计算属性
  const isRegistered = computed(() => {
    return registrationStatus.value?.status === '已报到'
  })

  const totalPaymentAmount = computed(() => {
    if (!paymentInfo.value?.items) return 0
    return paymentInfo.value.items.reduce((total, item) => total + item.amount, 0)
  })

  const paidAmount = computed(() => {
    if (!paymentHistory.value) return 0
    return paymentHistory.value
      .filter(record => record.status === '已完成')
      .reduce((total, record) => total + record.amount, 0)
  })

  const unpaidAmount = computed(() => {
    return totalPaymentAmount.value - paidAmount.value
  })

  const registrationProgress = computed(() => {
    if (!registrationStatus.value) return 0
    const steps = ['信息确认', '缴费完成', '宿舍分配', '报到确认']
    const currentStep = registrationStatus.value.currentStep || 0
    return Math.round((currentStep / steps.length) * 100)
  })

  // 获取学生信息
  const getStudentInfo = async () => {
    try {
      isLoading.value = true
      const response = await studentAPI.getStudentInfo()
      studentInfo.value = response.data
      return response
    } catch (error) {
      console.error('获取学生信息失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 更新学生信息
  const updateStudentInfo = async (data) => {
    try {
      const response = await studentAPI.updateStudentInfo(data)
      studentInfo.value = { ...studentInfo.value, ...data }
      return { success: true, message: '信息更新成功' }
    } catch (error) {
      return { success: false, message: error.message || '信息更新失败' }
    }
  }

  // 提交紧急联系人信息
  const submitEmergencyContact = async (data) => {
    try {
      await studentAPI.submitEmergencyContact(data)
      // 更新本地状态
      if (studentInfo.value) {
        studentInfo.value.emergencyContact = data
      }
      return { success: true, message: '紧急联系人信息提交成功' }
    } catch (error) {
      return { success: false, message: error.message || '提交失败' }
    }
  }

  // 获取报到状态
  const getRegistrationStatus = async () => {
    try {
      const response = await studentAPI.getRegistrationStatus()
      registrationStatus.value = response.data
      return response
    } catch (error) {
      console.error('获取报到状态失败:', error)
      throw error
    }
  }

  // 获取缴费信息
  const getPaymentInfo = async () => {
    try {
      const response = await studentAPI.getPaymentInfo()
      paymentInfo.value = response.data
      return response
    } catch (error) {
      console.error('获取缴费信息失败:', error)
      throw error
    }
  }

  // 在线缴费
  const makePayment = async (data) => {
    try {
      const response = await studentAPI.makePayment(data)
      // 刷新缴费信息
      await getPaymentInfo()
      await getPaymentHistory()
      return { success: true, message: '缴费成功', data: response.data }
    } catch (error) {
      return { success: false, message: error.message || '缴费失败' }
    }
  }

  // 获取缴费记录
  const getPaymentHistory = async () => {
    try {
      const response = await studentAPI.getPaymentHistory()
      paymentHistory.value = response.data
      return response
    } catch (error) {
      console.error('获取缴费记录失败:', error)
      throw error
    }
  }

  // 获取班级信息
  const getClassInfo = async () => {
    try {
      const response = await studentAPI.getClassInfo()
      classInfo.value = response.data
      return response
    } catch (error) {
      console.error('获取班级信息失败:', error)
      throw error
    }
  }

  // 获取宿舍信息
  const getDormitoryInfo = async () => {
    try {
      const response = await studentAPI.getDormitoryInfo()
      dormitoryInfo.value = response.data
      return response
    } catch (error) {
      console.error('获取宿舍信息失败:', error)
      throw error
    }
  }

  // 获取通知公告
  const getNotices = async (params = {}) => {
    try {
      const response = await studentAPI.getNotices(params)
      notices.value = response.data
      return response
    } catch (error) {
      console.error('获取通知公告失败:', error)
      throw error
    }
  }

  // 获取日程安排
  const getSchedule = async () => {
    try {
      const response = await studentAPI.getSchedule()
      schedule.value = response.data
      return response
    } catch (error) {
      console.error('获取日程安排失败:', error)
      throw error
    }
  }

  // 获取联系方式
  const getContactInfo = async () => {
    try {
      const response = await studentAPI.getContactInfo()
      contactInfo.value = response.data
      return response
    } catch (error) {
      console.error('获取联系方式失败:', error)
      throw error
    }
  }

  // 初始化学生数据
  const initStudentData = async () => {
    try {
      await Promise.all([
        getStudentInfo(),
        getRegistrationStatus(),
        getPaymentInfo(),
        getPaymentHistory()
      ])
    } catch (error) {
      console.error('初始化学生数据失败:', error)
    }
  }

  // 清除学生数据
  const clearStudentData = () => {
    studentInfo.value = null
    registrationStatus.value = null
    paymentInfo.value = null
    paymentHistory.value = []
    classInfo.value = null
    dormitoryInfo.value = null
    notices.value = []
    schedule.value = []
    contactInfo.value = null
  }

  return {
    // 状态
    studentInfo,
    registrationStatus,
    paymentInfo,
    paymentHistory,
    classInfo,
    dormitoryInfo,
    notices,
    schedule,
    contactInfo,
    isLoading,
    
    // 计算属性
    isRegistered,
    totalPaymentAmount,
    paidAmount,
    unpaidAmount,
    registrationProgress,
    
    // 方法
    getStudentInfo,
    updateStudentInfo,
    submitEmergencyContact,
    getRegistrationStatus,
    getPaymentInfo,
    makePayment,
    getPaymentHistory,
    getClassInfo,
    getDormitoryInfo,
    getNotices,
    getSchedule,
    getContactInfo,
    initStudentData,
    clearStudentData
  }
})